import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'dart:convert';
import 'package:get/get.dart';
// import 'package:image_picker_web/image_picker_web.dart';
import 'package:intl/intl.dart';
import 'package:pet/app/contants/my_colors.dart';
import 'package:pet/app/models/shortcut.dart';
import 'package:pet/app/widgets/custom_avatar.dart';
import 'package:pet/app/widgets/loading.dart';
import 'dart:math';
import '../../../websocket_controller.dart';
import '../../../widgets/breathe.dart';
import '../controllers/chat_controller.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:bubble/bubble.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class ChatView extends GetView<WebsocketController> {
  ChatView({Key? key}) : super(key: key);
  final arguments = Get.arguments;

  ChatController chatController = Get.find<ChatController>();

  @override
  Widget build(BuildContext context) {
    var id = arguments['id'];
    var sendId = arguments['sendId'];
    var chatAvatar = arguments['avatar'];
    var type = arguments['type'];

    /// 获取客户会话
    chatController.getConversations(id, sendId, type, '');
    final self = types.User(id: controller.memberId.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "和${arguments['nickname']}对话",
          style: const TextStyle(fontSize: 16, color: Colors.white),
        ),
        backgroundColor: MyColors.secondaryDark,
        centerTitle: true,
        toolbarHeight: 50,
        elevation: 1,
        actions: [
          Container(
            margin: const EdgeInsets.only(
              right: 10,
            ),
            child: CustomAvatar(
              avatar: chatAvatar,
              height: 40,
              width: 40,
            ),
          ),
          const Breathe()
        ],
      ),
      body: GetBuilder<WebsocketController>(
        init: WebsocketController(),
        builder: (controller) {
          return Stack(
            children: [
              !controller.isConnect ? const Loading() : const SizedBox(),
              Chat(
                customBottomWidget: (type == 'online' &&
                        controller.closeId != int.parse(id))
                    ? GetBuilder<ChatController>(builder: (controller) {
                        return Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                Get.dialog(
                                  barrierDismissible: true,
                                  Scaffold(
                                    backgroundColor: Colors.transparent,
                                    body: GetBuilder<WebsocketController>(
                                      builder: (controller) {
                                        List<Shortcut> data =
                                            controller.shortcutsData;
                                        return GestureDetector(
                                          onTap: () {
                                            Get.back();
                                          },
                                          child: Container(
                                            padding: const EdgeInsets.only(
                                              top: 100,
                                            ),
                                            child: ListView.builder(
                                              itemCount: data.length,
                                              itemBuilder: (context, index) {
                                                return Container(
                                                  margin: const EdgeInsets.only(
                                                      bottom: 10),
                                                  padding:
                                                      const EdgeInsets.all(8),
                                                  decoration:
                                                      const BoxDecoration(
                                                          // color: Colors.amber,
                                                          ),
                                                  child: GestureDetector(
                                                    onDoubleTap: () {
                                                      types.PartialText
                                                          message =
                                                          types.PartialText(
                                                              text: data[index]
                                                                  .content
                                                                  .toString());
                                                      _handleSendPressed(
                                                          message);
                                                      Get.back();
                                                    },
                                                    child: Text(
                                                      data[index]
                                                          .title
                                                          .toString(),
                                                      style: const TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 18,
                                                      ),
                                                    ),
                                                  ),
                                                );
                                              },
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                );
                              },
                              child: SizedBox(
                                height: 62,
                                width: Get.width * 0.2,
                                child: const Center(
                                  child: Icon(
                                    Icons.shortcut_sharp,
                                    size: 20,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              color: MyColors.secondaryDark,
                              width: Get.width * 0.8,
                              child: Input(
                                isAttachmentUploading: controller.upload,
                                onAttachmentPressed: _handleImageSelection,
                                onSendPressed: _handleSendPressed,
                              ),
                            ),
                          ],
                        );
                      })
                    : const SizedBox(),
                theme: const DarkChatTheme(),
                disableImageGallery: false,
                l10n: const ChatL10nEn(
                  inputPlaceholder: '输入消息',
                  emptyChatPlaceholder: '空空如也',
                  sendButtonAccessibilityLabel: '发送',
                  unreadMessagesLabel: '未读消息',
                ),
                messages: controller.messages[id] ?? [],
                // dateFormat: DateFormat('yyyy-MM-dd'),
                dateLocale: 'ZH_CN',
                onSendPressed: _handleSendPressed,
                // onAttachmentPressed: _handleImageSelection,
                user: self,
              )
            ],
          );
        },
      ),
    );
  }

  void _handleImageSelection() async {
    if (Platform.isAndroid) {
      final result = await ImagePicker().pickImage(
        imageQuality: 70,
        maxWidth: 1440,
        source: ImageSource.gallery,
      );

      ChatController chatController = Get.find<ChatController>();

      if (result != null) {
        final bytes = await result.readAsBytes();

        final image = await decodeImageFromList(bytes);

        // 转换类型
        File imageFile = File(result.path);

        chatController.uploading(true);
        var data = await chatController.uploadImage(imageFile);
        if (data.length == 0) {
          chatController.uploading(false);

          Get.snackbar("error", '发送图片失败');
        }
        chatController.uploading(false);

        final self = types.User(id: controller.memberId.toString());

        final imageMessage = types.ImageMessage(
          author: self,
          createdAt: DateTime.now().millisecondsSinceEpoch,
          height: image.height.toDouble(),
          id: randomString(),
          name: data['name'],
          size: data['size'],
          uri: data['url'],
          width: image.width.toDouble(),
        );
        controller.sendImageMessage(
            arguments['id'], arguments['sendId'], imageMessage);
      }
    }
    if (Platform.isWindows) {
      // List<Uint8List>? bytesFromPicker = await ImagePickerWeb.getMultiImagesAsBytes();
      // print(bytesFromPicker);
      Get.snackbar("提示", "PC端不支持发送图片", colorText: Colors.white);
    }
  }

  void _handleSendPressed(types.PartialText message) {
    final self = types.User(id: controller.memberId.toString());
    final textMessage = types.TextMessage(
      author: self,
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: randomString(),
      text: message.text,
    );

    controller.sendMessage(arguments['id'], arguments['sendId'], textMessage);
  }

  Widget _bubbleBuilder(
    Widget child, {
    required message,
    required nextMessageInGroup,
  }) {
    return Bubble(
      // stick: false,
      padding: BubbleEdges.all(0),
      // borderWidth: 2,
      // shadowColor:
      //     controller.memberId.toString() != message.author.id.toString()
      //         ? const Color.fromARGB(255, 109, 96, 229)
      //         : Colors.white,
      // borderColor:
      //     controller.memberId.toString() != message.author.id.toString()
      //         ? const Color.fromARGB(255, 109, 96, 229)
      //         : Colors.white,
      radius: const Radius.circular(8),
      color: controller.memberId.toString() != message.author.id.toString() ||
              message.type == types.MessageType.image
          ? const Color.fromARGB(255, 255, 255, 255)
          : const Color.fromARGB(255, 109, 96, 229),
      margin: nextMessageInGroup
          ? const BubbleEdges.symmetric(horizontal: 6)
          : null,
      nip: nextMessageInGroup
          ? BubbleNip.no
          : controller.memberId.toString() != message.author.id.toString()
              ? BubbleNip.no
              : BubbleNip.rightCenter,
      child: child,
    );
  }
}

String randomString() {
  final random = Random.secure();
  final values = List<int>.generate(16, (i) => random.nextInt(255));
  return base64UrlEncode(values);
}
